package cn.bellychang.leetcode.question025;

/**
 * @author ChangLiang
 * @date 2021/3/16
 */
public class Solution {

    public ListNode reverseKGroup(ListNode head, int k) {

        if (head == null) {
            return null;
        }

        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode prev = head;
        ListNode curr = head.next;
        ListNode next;
        ListNode tail = dummyHead;

        ListNode beginIndex = head;

        int i = 1;

        while (needReverse(beginIndex, k)) {


            next = curr.next;

            ListNode temp = beginIndex;
            for (int j = 0; j < k; j++) {
                temp = temp.next;
            }
            prev.next = temp;

            while(i % k != 0){
                curr.next = prev;
                prev = curr;
                curr = next;

                i++;
            }
            i = 1;
            tail.next = prev;
            tail = beginIndex;
            beginIndex = curr;
            if (beginIndex == null) {
                break;
            }
            prev = curr;
            curr = curr.next;
        }

        return dummyHead.next;
    }

    private boolean needReverse(ListNode head, int k) {
        for (int i = 0; i < k-1; i++) {
            if (head == null) {
                return false;
            }
            head = head.next;
        }
        return true;
    }
}
